import { useUserStore } from '@/stores/user'
import axios, { type Method } from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router'
const service = axios.create({
  baseURL: 'https://api-hmzs.itheima.net/tj',
  timeout: 20 * 1000,
})

export interface ServiceResponse<T> {
  code: number
  msg: string
  data: T
}
export const request = <T>(url: string, method: Method = 'GET', submitData?: object) => {
  return service.request<T, ServiceResponse<T>>({
    url: url,
    method: method,
    [method.toUpperCase() === 'GET' ? 'params' : 'data']: submitData
  })
}

service.interceptors.request.use(
  config => {
    const store = useUserStore()
    if(store.token){
      config.headers.Authorization = `Bearer ${store.token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  },
)

service.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    if (error.response) {
      ElMessage.error(error.response.data.msg)
      if (error.status === 401){
        router.push('/login')
        const store = useUserStore()
        store.clearToken()
      }
    }else{
      ElMessage.error('请求失败，请稍后再试')
    }
    return Promise.reject(error)
  },
)

export default service